package com.snail.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.common.DeleteRequest;
import com.snail.mapper.BizCourseOutlinesMapper;
import com.snail.mapper.BizCoursesBaseMapper;
import com.snail.mapper.BizMediaFileMapper;
import com.snail.model.dto.CourseBaseDto;
import com.snail.model.dto.CourseOutlinesTreeDto;
import com.snail.model.pojo.BizCourseOutlines;
import com.snail.model.pojo.BizCoursesBase;
import com.snail.model.pojo.BizMediaFile;
import com.snail.response.BaseResponse;
import com.snail.response.ResultUtils;
import com.snail.service.BizCourseOutlinesService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author Monica
* @description 针对表【biz_course_outlines(课程大纲结构表，支持章-节两级结构)】的数据库操作Service实现
* @createDate 2025-07-17 13:16:38
*/
@Service
public class BizCourseOutlinesServiceImpl extends ServiceImpl<BizCourseOutlinesMapper, BizCourseOutlines>
    implements BizCourseOutlinesService {
    @Autowired
    private BizCourseOutlinesMapper bizCourseOutlinesMapper;
    @Autowired
    private BizCoursesBaseMapper bizCoursesBaseMapper;
    @Autowired
    private BizMediaFileMapper bizMediaFileMapper;

    @Override
    public BaseResponse<List<CourseOutlinesTreeDto>> getCourseOutlines(Integer courseId) {
        // 1. 查询所有未删除的大纲数据
        LambdaQueryWrapper<BizCourseOutlines> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizCourseOutlines::getCourseId, courseId);
        List<BizCourseOutlines> allOutlines = bizCourseOutlinesMapper.selectList(queryWrapper);

        // 2. 构建树形结构
        List<CourseOutlinesTreeDto> tree = buildOutlinesTree(allOutlines);

        // 3. 返回成功响应
        return ResultUtils.success(tree);
    }

    @Override
    public BaseResponse<Boolean> saveCourseOutlines(BizCourseOutlines bizCourseOutlines) {
        // 1. 校验数据
        if (bizCourseOutlines.getParentId() != null) {
            // 非顶级大纲，需要校验父大纲是否存在
            BizCourseOutlines parentOutline = bizCourseOutlinesMapper.selectById(bizCourseOutlines.getParentId());
            if (parentOutline == null) {
                return ResultUtils.success(false);
            }
        }

        // 2. 保存大纲
        boolean success = save(bizCourseOutlines);

        // 3. 返回响应
        return ResultUtils.success(success);
    }

    @Override
    public BaseResponse<Boolean> updateCourseOutlines(BizCourseOutlines bizCourseOutlines) {
        // 1. 校验数据
        if (bizCourseOutlines.getParentId() != null) {
            // 非顶级大纲，需要校验父大纲是否存在
            BizCourseOutlines parentOutline = bizCourseOutlinesMapper.selectById(bizCourseOutlines.getParentId());
            if (parentOutline == null) {
                return ResultUtils.success(false);
            }
        }

        // 2. 更新大纲
        boolean success = updateById(bizCourseOutlines);

        // 3. 返回响应
        return ResultUtils.success(success);
    }

    @Override
    public BaseResponse<Boolean> deleteCourseOutlines(DeleteRequest deleteRequest) {
        if (deleteRequest.getId() == null) {
            return ResultUtils.success(false);
        }
        boolean success = removeById(deleteRequest.getId());
        return ResultUtils.success(success);
    }

    @Override
    public BaseResponse<CourseBaseDto> getCourseBaseById(Long id) {
        BizCoursesBase coursesBase = bizCoursesBaseMapper.selectById(id);
        if (coursesBase == null) {
            return null;
        }
        CourseBaseDto courseBaseDto = new CourseBaseDto();
        BeanUtils.copyProperties(coursesBase, courseBaseDto);
        LambdaQueryWrapper<BizCourseOutlines> outlinesQueryWrapper = new LambdaQueryWrapper<>();
        outlinesQueryWrapper.eq(BizCourseOutlines::getCourseId, coursesBase.getId());
        List<BizCourseOutlines> bizCourseOutlines = bizCourseOutlinesMapper.selectList(outlinesQueryWrapper);
        List<CourseOutlinesTreeDto> courseOutlinesTreeDtos = buildOutlinesTree(bizCourseOutlines);



        courseBaseDto.setOutlineList(courseOutlinesTreeDtos);

        return ResultUtils.success(courseBaseDto);
    }

    /**
     * 构建大纲树形结构
     * @param allOutlines 所有大纲列表
     * @return 树形结构列表
     */
    private List<CourseOutlinesTreeDto> buildOutlinesTree(List<BizCourseOutlines> allOutlines) {
        // 1. 创建DTO映射Map和结果列表
        Map<Integer, CourseOutlinesTreeDto> dtoMap = new HashMap<>();
        List<CourseOutlinesTreeDto> result = new ArrayList<>();

        // 2. 先处理所有大纲，创建DTO对象并放入Map
        for (BizCourseOutlines outline : allOutlines) {
            CourseOutlinesTreeDto dto = convertToDto(outline);
            dtoMap.put(dto.getId(), dto);
        }

        // 3. 构建树形结构
        for (CourseOutlinesTreeDto dto : dtoMap.values()) {
            Integer parentId = dto.getParentId();
            if (parentId == null || parentId == 0) {
                // 顶级大纲，直接加入结果列表
                result.add(dto);
            } else {
                // 子大纲，找到父大纲并添加到父大纲的children中
                CourseOutlinesTreeDto parentDto = dtoMap.get(parentId);
                if (parentDto != null) {
                    if (parentDto.getChildren() == null) {
                        parentDto.setChildren(new ArrayList<>());
                    }
                    parentDto.getChildren().add(dto);
                }
            }
        }

        // 4. 对每层的大纲按sort_order排序
        sortOutlinesTree(result);

        return result;
    }

    /**
     * 将实体转换为DTO
     */
    private CourseOutlinesTreeDto convertToDto(BizCourseOutlines outline) {
        CourseOutlinesTreeDto dto = new CourseOutlinesTreeDto();
        dto.setId(outline.getId());
        dto.setTitle(outline.getTitle());
        dto.setParentId(outline.getParentId());
        dto.setSortOrder(outline.getSortOrder());
        dto.setVideoId(outline.getVideoId());
        BizMediaFile bizMediaFile = bizMediaFileMapper.selectById(outline.getVideoId());
        if (bizMediaFile != null) {
            dto.setFilePath(bizMediaFile.getFilePath());
        }
        return dto;
    }

    /**
     * 对大纲树进行排序（按sort_order升序）
     */
    private void sortOutlinesTree(List<CourseOutlinesTreeDto> tree) {
        if (tree == null) {
            return;
        }

        // 排序当前层级
        tree.sort(Comparator.comparingInt(dto -> {
            // 这里需要根据sort_order排序，但DTO中没有这个字段
            // 可以在DTO中添加sortOrder字段，或者在查询时缓存sortOrder
            // 假设我们修改了DTO，添加了sortOrder字段
            return dto.getSortOrder() != null ? dto.getSortOrder() : 0;
        }));

        // 递归排序子层级
        for (CourseOutlinesTreeDto dto : tree) {
            if (dto.getChildren() != null && !dto.getChildren().isEmpty()) {
                sortOutlinesTree(dto.getChildren());
            }
        }
    }
}




